<template>
	<el-drawer v-model="visible" title="更新附件" :size="1200" :with-header="false">
		<!-- @keyup.enter="submitHandle()" -->
		<el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="120px">
			<el-tabs v-model="activeName">
				<el-tab-pane label="基本信息" name="basicInfo">
					<el-form-item prop="pid" label="上级模板">
						<ma-template-select v-model="dataForm.pid" placeholder="请选择"></ma-template-select>
					</el-form-item>
					<el-form-item label="模板名称" prop="templateName">
						<el-input v-model="dataForm.templateName" placeholder="模板名称"></el-input>
					</el-form-item>
					<el-form-item label="模板截图" prop="templateImg">
						<el-upload
							class="avatar-uploader"
							:action="avatarUploadUrl"
							:show-file-list="false"
							:on-success="handleAvatarSuccess"
							:before-upload="beforeAvatarUpload"
						>
							<img v-if="imageUrl" :src="imageUrl" class="avatar" />
							<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
						</el-upload>
					</el-form-item>
					<el-form-item label="模板压缩包文件" prop="templateZip">
						<el-upload
							ref="fileUploadRef"
							class="file-uploader"
							:action="fileUploadUrl"
							:before-upload="beforeZipUpload"
							:on-success="handleZipSuccess"
							:on-exceed="handleExceed"
							:limit="1"
						>
							<el-button type="primary">选择模板压缩包zip文件</el-button>
							<template #tip>
								<div class="el-upload__tip">只能上传10M以下的zip文件</div>
							</template>
						</el-upload>
					</el-form-item>
					<!-- <el-form-item label="模板压缩包路径" prop="templatePath">
						<el-input v-model="dataForm.templatePath" placeholder="模板压缩包路径"></el-input>
					</el-form-item> -->
					<el-form-item label="版本号" prop="version">
						<el-input-number v-model="dataForm.version" :min="1" :max="10" />
					</el-form-item>
				</el-tab-pane>
				<el-tab-pane label="模板说明" name="templateDesc">
					<el-row>
						<el-col :span="12">
							<el-form-item label="模板描述" prop="readmeContent">
								<el-input v-model="dataForm.readmeContent" type="textarea" rows="30" cols="50" placeholder="模板描述" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="描述展示">
								<div v-html="renderedMarkdown"></div>
							</el-form-item>
						</el-col>
					</el-row>
				</el-tab-pane>
			</el-tabs>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" @click="submitHandle()">确定</el-button>
		</template>
	</el-drawer>
</template>

<script setup lang="ts">
import { reactive, ref, computed } from 'vue'
import { ElMessage } from 'element-plus/es'
import { Plus } from '@element-plus/icons-vue'
import MaTemplateSelect from '@/components/ma-template/ma-template-select/index.vue'
import type { UploadInstance, UploadProps, UploadUserFile } from 'element-plus'

import MarkdownIt from 'markdown-it'
import { useGen_template_treeApi, useGen_template_treeSubmitApi } from '@/api/genTemplateTree'

const PUBLIC_URL = import.meta.env.VITE_API_URL
const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const activeName = ref()
const dataFormRef = ref()

const dataForm = reactive({
	id: '',
	pid: '',
	templateName: '',
	parentName: '',
	templateImg: '',
	readmeContent: '# 示例说明 \n\r ## 示例说明',
	readmeFile: '',
	templateZip: '',
	templatePath: '',
	createTime: '',
	version: ''
})

const mdi = new MarkdownIt({
	html: false,
	linkify: true
})

// 处理并渲染Markdown内容
const renderedMarkdown = computed(() => {
	return mdi.render(dataForm.readmeContent)
	// return dataForm.readmeContent
})

const init = (isUpdate: boolean, row: any) => {
	visible.value = true
	activeName.value = 'basicInfo'

	// 重置表单数据
	// 重置表单数据
	if (dataFormRef.value) {
		dataFormRef.value.resetFields()
	}
	imageUrl.value = ''

	if (!isUpdate) {
		// 是新增
		if (row) {
			dataForm.pid = row.id
			dataForm.parentName = row.parentName
		}
	} else {
		getGenTemplateTree(row.id)
		imageUrl.value = PUBLIC_URL + dataForm.templateImg
	}
}

const getGenTemplateTree = (id: number) => {
	useGen_template_treeApi(id).then(res => {
		Object.assign(dataForm, res.data)
		imageUrl.value = PUBLIC_URL + dataForm.templateImg
	})
}

const dataRules = ref({
	templateName: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	templateImg: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	templateZip: [{ required: true, message: '必填项不能为空', trigger: 'blur' }]
})

const imageUrl = ref('')
const avatarUploadUrl = PUBLIC_URL + '/gen/fileUpDownLoad/uploadFile/IMAGE'

// 表单提交
const submitHandle = () => {
	dataFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			return false
		}

		useGen_template_treeSubmitApi(dataForm).then(() => {
			fileUploadRef.value!.clearFiles() //清空上传列表
			imageUrl.value = ''

			ElMessage.success({
				message: '操作成功',
				duration: 500,
				onClose: () => {
					visible.value = false
					emit('refreshDataList')
				}
			})
		})
	})
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
	// imageUrl.value = URL.createObjectURL(uploadFile.raw!)
	// console.log(response.data)
	dataForm.templateImg = response.data
	imageUrl.value = PUBLIC_URL + dataForm.templateImg
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = rawFile => {
	if (rawFile.type !== 'image/jpeg') {
		ElMessage.error('Avatar picture must be JPG format!')
		return false
	} else if (rawFile.size / 1024 / 1024 > 2) {
		ElMessage.error('Avatar picture size can not exceed 2MB!')
		return false
	}
	return true
}

const fileUploadUrl = PUBLIC_URL + '/gen/fileUpDownLoad/uploadFile/ZIP'
const fileUploadRef = ref<UploadInstance>()

const beforeZipUpload: UploadProps['beforeUpload'] = rawFile => {
	// console.log(rawFile.type)
	if (rawFile.type !== 'application/zip') {
		ElMessage.error('Base package picture must be zip format!')
		return false
	} else if (rawFile.size / 1024 / 1024 > 50) {
		ElMessage.error('Avatar picture size can not exceed 10MB!')
		return false
	}
	return true
}

const handleExceed = () => {
	ElMessage.error('只能上传一个文件!')
}

const handleZipSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
	console.log(response.data)
	dataForm.templateZip = response.data
}

defineExpose({
	init
})
</script>
<style scoped>
.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	text-align: center;
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
}

.file-uploader {
	width: 200px;
	height: 100px;
	display: block;
}
</style>
